//
//  ComUtil.m
//  HiZhua
//
//  Created by Jpwang on 2017/8/7.
//  Copyright © 2017年 Jpwang. All rights reserved.
//

#import "ComUtil.h"

@implementation ComUtil
id isNil(id value) {
    if (value == nil || [value isKindOfClass:[NSNull class]] ) {
        return nil;
    }
    return value;
}

BOOL isHexNumber(NSString *text) {
    NSString *hexRegex = @"^[A-Fa-f0-9]+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", hexRegex];
    return [emailTest evaluateWithObject:text];
}

/*邮箱验证 MODIFIED BY HELENSONG*/
BOOL isValidEmail(NSString *email) {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//17198935383
BOOL isValidMobile(NSString *mobile) {
    NSString *phoneRegex = @"^[1]\\d{10}$";
//    NSString *phoneRegex = @"^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

NSString *currentTimeMillis() {
    return [NSString stringWithFormat:@"%lld",(long long)([[NSDate date] timeIntervalSince1970]*1000)];
}

NSString *appVersion() {
    NSString *version = @"";
    version = [version stringByAppendingString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    return version;
}

NSString *systemVersion() {
    return [[UIDevice currentDevice] systemVersion];
}

void saveValueByKey(id value, NSString *key) {
    @try {
        if (value == nil || [value isKindOfClass:[NSNull class]]) {
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
        } else {
            if ([value isKindOfClass:[NSDictionary class]]) {
                NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:value];
                for (id temp in dic.allKeys) {
                    if (temp == nil || [temp isKindOfClass:[NSNull class]]) {
                        [dic removeObjectForKey:temp];
                    }
                }
                [[NSUserDefaults standardUserDefaults] setObject:dic forKey:key];
            } else if ([value isKindOfClass:[NSArray class]]) {
                NSMutableArray *arr = [[NSMutableArray alloc] initWithArray:value];
                for (id temp in arr) {
                    if (temp == nil || [temp isKindOfClass:[NSNull class]]) {
                        [arr removeObject:temp];
                    }
                }
                [[NSUserDefaults standardUserDefaults] setObject:arr forKey:key];
            } else {
                [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
            }
            
        }
        [[NSUserDefaults standardUserDefaults] synchronize];
    } @catch (NSException *exception) {
        
    }
}

id getValueByKey(NSString *key) {
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

void removeValueByKey(NSString *key) {
    return [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}

NSString *intToString(NSInteger number) {
    return [NSString stringWithFormat:@"%ld", number];
}

NSString *NSStringFromCATransform3D(CATransform3D transform) {
    return [NSString stringWithFormat:@"\n\n m11=%f, m12=%f, m13=%f, m14=%f,\n m21=%f, m22=%f, m23=%f, m24=%f,\n m31=%f, m32=%f, m33=%f, m34=%f,\n m41=%f, m42=%f, m43=%f, m44=%f \n\n",transform.m11, transform.m12, transform.m13, transform.m14, transform.m21, transform.m22, transform.m23, transform.m24, transform.m31, transform.m32, transform.m33, transform.m34, transform.m41, transform.m42, transform.m43, transform.m44];
}

float getTextWidth(NSString *text, float width, float fontsize) {
    if (text == nil) {
        return 0;
    }
    UIFont *font = [UIFont systemFontOfSize:fontsize];
    NSDictionary *dic = @{NSFontAttributeName:font};
    return [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size.width;
}


BOOL isInstallQQ() {
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]];
}

BOOL isInstallWX() {
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]];
}

BOOL isInstallSina() {
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"sinaweibosso://"]];
}

NSString* dataToJson(id object) {
    NSString *jsonString = nil;
    @try {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                           options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                             error:&error];
        if (!jsonData) {
            NSLog(@"Got an error: %@", error);
        } else {
            jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
    } @catch (NSException *exception) {
        
    }
    return jsonString;
}

id string2Json(NSString *str) {
    NSError *error;
    NSString *requestTmp = [NSString stringWithString: str];
    NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
    return [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:&error];  
}

NSString *urlEncode(NSStringEncoding encoding, NSString *url) {
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( NULL, (__bridge CFStringRef)url, NULL, (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding)));
}


NSDictionary* getObjectData(id obj) {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    unsigned int propsCount;
    objc_property_t *props = class_copyPropertyList([obj class], &propsCount);
    for(int i = 0;i < propsCount; i++) {
        objc_property_t prop = props[i];
        NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
        id value = [obj valueForKey:propName];
        if(value == nil) {
            value = [NSNull null];
        } else {
            value = getObjectInternal(value);
        }
        [dic setObject:value forKey:propName];
    }
    return dic;
}

id getObjectInternal(id obj) {
    if([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]] || [obj isKindOfClass:[NSNull class]]) {
        return obj;
    }
    if([obj isKindOfClass:[NSArray class]]) {
        NSArray *objarr = obj;
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
        for(int i = 0; i < objarr.count; i++) {
            [arr setObject:getObjectInternal([objarr objectAtIndex:i]) atIndexedSubscript:i];
        }
        return arr;
    }
    if([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *objdic = obj;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
        for(NSString *key in objdic.allKeys) {
            [dic setObject:getObjectInternal([objdic objectForKey:key]) forKey:key];
        }
        return dic;
    }
    return  getObjectData(obj);
}

NSString *dicToJSONString(NSDictionary *dic) {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}


//裁剪图片
UIImage *clipImageWithCornerRadius(CGFloat cornerRadius, UIImage *originImage) {
    CGFloat w = originImage.size.width;
    CGFloat h = originImage.size.height;
    CGFloat scale = [UIScreen mainScreen].scale;
    // 防止圆角半径小于0，或者大于宽/高中较小值的一半。
    if (cornerRadius < 0) {
        cornerRadius = 0;
    } else if (cornerRadius > MIN(w, h)) {
        cornerRadius = MIN(w, h)/2.0;
    }
    
    UIImage *image = nil;
    CGRect imageFrame = CGRectMake(0., 0., w, h);
    UIGraphicsBeginImageContextWithOptions(originImage.size, NO, scale);
    [[UIBezierPath bezierPathWithRoundedRect:imageFrame cornerRadius:cornerRadius] addClip];
    [originImage drawInRect:imageFrame];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

UIImage *createImageOfLC(float cornerRadius, CGSize size, UIColor *color) {
    UIGraphicsBeginImageContext(size);
    // 获取当前图形上下文
    CGContextRef c = UIGraphicsGetCurrentContext();
    // 填充
    CGContextSetFillColorWithColor(c, color.CGColor);
    CGContextMoveToPoint(c, size.width, 0);
    CGContextAddLineToPoint(c, size.width, size.height);
    CGContextAddLineToPoint(c, size.width-cornerRadius, size.height);
    CGContextAddArc(c, cornerRadius, size.height-cornerRadius, cornerRadius, M_PI/2, M_PI, 0);
    CGContextAddLineToPoint(c, 0, cornerRadius);
    CGContextAddArc(c, cornerRadius, cornerRadius, cornerRadius, M_PI, M_PI*3/2, 0);
    CGContextClosePath(c);
    CGContextFillPath(c);
    // 从当前图形上下文中获取一张透明图片
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭图形绘制
    UIGraphicsEndImageContext();
    img = stretchImage(img, UIEdgeInsetsMake(0, size.width-1, 0, 0));
    return img;
}
UIImage *createImageOfRC(float cornerRadius, CGSize size, UIColor *color) {
    UIGraphicsBeginImageContext(size);
    // 获取当前图形上下文
    CGContextRef c = UIGraphicsGetCurrentContext();
    // 填充
    CGContextSetFillColorWithColor(c, color.CGColor);
    CGContextMoveToPoint(c, size.width-cornerRadius, 0);
    CGContextAddArc(c, size.width-cornerRadius, cornerRadius, cornerRadius, M_PI*3/2, M_PI*2, 0);
    CGContextAddLineToPoint(c, size.width, size.height-cornerRadius);
    CGContextAddArc(c, size.width-cornerRadius, size.height-cornerRadius, cornerRadius, 0, M_PI/2, 0);
    CGContextAddLineToPoint(c, 0, size.height);
    CGContextAddLineToPoint(c, 0, 0);
    CGContextClosePath(c);
    CGContextFillPath(c);
    // 从当前图形上下文中获取一张透明图片
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭图形绘制
    UIGraphicsEndImageContext();
    img = stretchImage(img, UIEdgeInsetsMake(0, 0, 0, size.width-1));
    return img;
}
UIImage *createImageOfTC(float cornerRadius, CGSize size, UIColor *color) {
    UIGraphicsBeginImageContext(size);
    // 获取当前图形上下文
    CGContextRef c = UIGraphicsGetCurrentContext();
    // 填充
    CGContextSetFillColorWithColor(c, color.CGColor);
    CGContextMoveToPoint(c, size.width-cornerRadius, 0);
    CGContextAddArc(c, size.width-cornerRadius, cornerRadius, cornerRadius, M_PI*3/2, M_PI*2, 0);
    CGContextMoveToPoint(c, size.width, size.height);
    CGContextAddLineToPoint(c, 0, size.height);
    CGContextAddLineToPoint(c, 0, size.height-cornerRadius);
    CGContextAddArc(c, cornerRadius, cornerRadius, cornerRadius, M_PI, M_PI*3/2, 0);
    CGContextClosePath(c);
    CGContextFillPath(c);
    // 从当前图形上下文中获取一张透明图片
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭图形绘制
    UIGraphicsEndImageContext();
    img = stretchImage(img, UIEdgeInsetsMake(size.height-1, 0, 0, 0));
    return img;
}


UIImage *createImageOfBC(float cornerRadius, CGSize size, UIColor *color) {
    UIGraphicsBeginImageContext(size);
    // 获取当前图形上下文
    CGContextRef c = UIGraphicsGetCurrentContext();
    // 填充
    CGContextSetFillColorWithColor(c, color.CGColor);
    CGContextMoveToPoint(c, size.width, 0);
    CGContextAddLineToPoint(c, size.width, size.height-cornerRadius);
    CGContextAddArc(c, size.width-cornerRadius, size.height-cornerRadius, cornerRadius, 0, M_PI/2, 0);
    CGContextAddLineToPoint(c, 0, size.height-cornerRadius);
    CGContextAddArc(c, cornerRadius, size.height-cornerRadius, cornerRadius, M_PI/2, M_PI, 0);
    CGContextAddLineToPoint(c, 0, 0);
    CGContextClosePath(c);
    CGContextFillPath(c);
    // 从当前图形上下文中获取一张透明图片
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭图形绘制
    UIGraphicsEndImageContext();
    img = stretchImage(img, UIEdgeInsetsMake(0, 0, size.height-1, 0));
    return img;
}

UIImage *stretchImage(UIImage *img, UIEdgeInsets insets) {
    img = [img resizableImageWithCapInsets:insets];
    return img;
}

UIImage *createGradientImage(CGSize size, UIColor *color1, UIColor *color2, int direct) {
    UIGraphicsBeginImageContext(size);
    // 获取当前图形上下文
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = { 0.0, 1.0 };
    NSArray *colors = @[(__bridge id) color1.CGColor, (__bridge id) color2.CGColor];
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
    CGContextDrawLinearGradient(c, gradient, CGPointMake(0, 0), direct==0?CGPointMake(size.width, 0):CGPointMake(0, size.height), 0);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭图形绘制
    UIGraphicsEndImageContext();
    return img;
}

BOOL isIPhone5() {
    return ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO);
}


@end
